from rest_framework import serializers
from . import models


class Email(serializers.ModelSerializer):
    fu_jian_dc_ls = serializers.SerializerMethodField()

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        return ret

    def get_fu_jian_dc_ls(self, instance):
        obj = vars(instance)
        fu_jian_id = obj.get('fu_jian_id').replace('；', ';')
        fu_jian_shu_liang = obj.get('fu_jian_shu_liang').replace('；', ';')
        try:
            id_ls = fu_jian_id.split(';')
            num_ls = fu_jian_shu_liang.split(';')
            assert len(id_ls) == len(num_ls), '`id_ls`和`num_ls`的数量不相等!'
            fu_jian_dc_ls = []
            for id_i, num_i in zip(id_ls, num_ls):
                fu_jian_dc_ls.append(
                    {
                        'id': id_i,
                        'num': int(num_i),
                    }
                )
        except Exception as e:
            _id = obj.get('id')
            raise ValueError(f"ID[{_id}]提取`fu_jian_ls`时出现错误, 可能是`;`号数量不相等? error: {e}")
        return fu_jian_dc_ls

    class Meta:
        model = models.Email
        fields = '__all__'
